package com.aio.news.category.adapter;

import java.util.ArrayList;
import java.util.List;

import com.aidi.lib.TAInjectView;
import com.aio.news.AioApplication;
import com.aio.news.BaseFragment;
import com.aio.news.R;
import com.aio.news.category.fragment.CategoryListFragment;
import com.aio.news.model.CategoryModel.CategoryItem;
import com.aio.news.utils.AppConstance;
import com.squareup.picasso.Picasso;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CategoryAdapter extends BaseAdapter {

	private BaseFragment fragment;
	private List<CategoryItem> mItems = new ArrayList<CategoryItem>();

	public CategoryAdapter(BaseFragment mFragment) {
		this.fragment = mFragment;
	}

	public void addItems(List<CategoryItem> item) {
		this.mItems.addAll(item);
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return mItems.size();
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final CategoryItem item = mItems.get(position);
		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = View.inflate(fragment.getActivity(),
					R.layout.category_adapter_layout, null);
			AioApplication.getInjector().injectView(convertView, holder);
			int h = AppConstance.SCREEN_WIDTH / 3;
			convertView.setLayoutParams(new AbsListView.LayoutParams(h, h));
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		if(!TextUtils.isEmpty(item.url)){
			holder.img.setVisibility(View.VISIBLE);
			Picasso.with(fragment.getActivity()).load(item.url).into(holder.img);
		}else{
			holder.img.setVisibility(View.GONE);
		}
		if (!TextUtils.isEmpty(item.name)) {
			holder.name.setText(item.name);
		} else {
			holder.name.setText("");
		}
		convertView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Bundle b = new Bundle();
				b.putString("name", item.name);
				b.putInt("type", item.type);
				fragment.startFullFragment(CategoryListFragment.class, b);
			}
		});
		return convertView;
	}

	class ViewHolder {
		@TAInjectView(id = R.id.name)
		TextView name;
		@TAInjectView(id = R.id.img)
		ImageView img;
	}

}
